package me.ahoukuse.koala.controller;

import com.alibaba.fastjson2.JSONObject;
import me.ahoukuse.koala.dao.FileEntityDao;
import me.ahoukuse.koala.dao.UserDao;
import me.ahoukuse.koala.po.FileEntity;
import me.ahoukuse.koala.po.User;
import me.ahoukuse.koala.util.JwtUtil;
import me.ahoukuse.koala.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserDao userDao;

    @Autowired
    FileEntityDao fileEntityDao;

    @RequestMapping(value = "getFiles", method = RequestMethod.GET)
    public JSONObject getFiles(int parentId) {
        int userId = JwtUtil.getUserIdFromJwt();
        List<FileEntity> fileEntities = fileEntityDao.getFiles(userId, parentId);
        int filesCount = fileEntityDao.getFilesCount(userId, parentId);
        JSONObject res = MessageUtil.msg(200, "success");
        JSONObject data = new JSONObject();
        data.put("count", filesCount);
        data.put("files", fileEntities);
        res.put("data", data);
        return res;
    }



    @RequestMapping(value = "mkDir", method = RequestMethod.POST)
    public JSONObject createDir(Integer parentId, String dirName) {
        int userId = JwtUtil.getUserIdFromJwt();
        FileEntity entity = new FileEntity();
        entity.setFileName(dirName);
        entity.setType(1);
        entity.setOwnerId(userId);
        entity.setParentId(parentId);
        entity.setCreateTime(new Date());

        fileEntityDao.insertOne(entity);

        JSONObject res = MessageUtil.msg(200, "success");

        return res;
    }

    @RequestMapping(value = "signup", method = RequestMethod.POST)
    public JSONObject signUp(String userName, String password) {
        User user = userDao.findByUserName(userName);
        if (user != null) {
            return MessageUtil.msg(400, "该用户名已被注册，请更换");
        }
        userDao.insertOne(userName, password);
        return MessageUtil.msg(200, "Ok");
    }

}
